<template>
  <section :class="!showButton ? 'noButton' : null">
    <section class="groupDetail noDrag" :class="sm ? 'sm' : null" v-if="data">
      <el-avatar :size="60" :src="data?.group?.portrait" />
      <p class="name">{{ data?.group?.name }}</p>
      <div class="group_title">
        <img src="local-media://icons/msg.png" alt="">
        <span>群公告</span>
        <img src="local-media://group_close.png" alt="" class="arrow" />
      </div>
      <div class="notice">
        {{ data?.group?.notice }}
      </div>
      <div class="group_myinfo">
        <img src="local-media://icons/group_p.png" alt="">
        <span>我在本群昵称</span>
        <div class="arrow">
          <input type="text" v-model="data.myGroupNickname" @blur="editRemarkAction" maxlength="10" minlength="1"
            placeholder="请输入本群个人昵称">
          <img src="local-media://group_close.png" alt="" class="arrow" />
        </div>
      </div>

      <div class="group_all">
        <img src="local-media://icons/group_all.png" alt="">
        <span>群成员（{{ data?.user?.length }}人）</span>
      </div>
      <div class="thumbnail">
        <template v-for="(item, index) in data?.user">
          <el-avatar :size="40" :src="item?.portrait" v-if="(index < 5)" />
        </template>
      </div>
      <template v-if="showButton">
        <SubmitButton @submit="enterGroup" text="进入群聊" style="margin-top: 42px;font-size: 16px;" />
        <span class="exit" @click="logoutAction">
          {{ data.value?.master === "Y" ? "解散群聊" : "退出群聊" }}
        </span>
      </template>
    </section>
    <slot v-else></slot>
  </section>
</template>
<script>
import SubmitButton from '@/components/Login/SubmitButton.vue';
import { defineComponent, inject, computed } from 'vue';
import { getGroupDetail, logoutGroup, dismissGroup, } from '@/server/friend'
import { editGroupPersonName, getGroupDetailByCard } from '@/server/group'
import { useRequest } from 'vue-hooks-plus';
import { useStore } from "vuex"
import { v4 as uuidv4 } from 'uuid';
import { handelNotice } from '@/tool/useWebsokect'
import { db } from "@/config/data";
export default defineComponent({
  props: {
    groupId: {
      type: String,
      default: () => ''
    },
    sm: {
      type: Boolean,
      default: () => false
    },
    showButton: {
      type: Boolean,
      default: () => true
    }
  },
  components: {
    SubmitButton
  },
  setup (props, { emit }) {
    const store = useStore()
    const ready = computed(() => props?.groupId !== '')
    let { data } = useRequest(() => getGroupDetail(props?.groupId), {
      ready,
      refreshDeps: [() => props?.groupId],
    })

    const { run: logoutAction } = useRequest(async () => {
      const res = await window.electronAPI.showMessage({
        type: 'question',
        buttons: ['Yes', 'No'],
        title: '提示',
        message: '是否要退出群聊?'
      })
      if (res == 1) return Promise.reject()
      data.value = {}
      return data.value?.master === "Y" ? dismissGroup(props?.groupId) : logoutGroup(props?.groupId)
    }, {
      onSuccess: async res => {
        await db.conversation.where({ groupId: props?.groupId }).delete()
        store.dispatch('getFriendByType', {
          index: '0',
          params: 'default'
        })
      },
      manual: true,
      onError: err => {
      }
    })

    const { run: editName } = useRequest(editGroupPersonName, {
      manual: true
    })


    const enterGroup = async () => {
      const params = { value: data.value }
      const search = { groupId: props?.groupId, msgCustomType: 1 }
      const bands = await db.conversation.get(search)
      if (bands) {
        //查询会话列表有这个窗口了,直接选中
        store.commit('saveSelectSession', bands)
        await db.conversation.where({ uuid: bands.uuid }).modify({ timestamp: new Date().getTime() })
      } else {
        //创建新的会话窗口
        const customMsg = {
          msgId: uuidv4(),
          pushType: "MSG",
          timestamp: new Date().getTime(),
          msgContent: {
            content: "",
            disturb: params.value?.set.disturb,
            msgType: "TEXT",
            top: params.value?.set.top
          },
          fromInfo: {
          },
          groupInfo: {
            nickName: params.value.group?.name,
            portrait: params.value.group?.portrait,
            userId: params.value.group?.groupId,
          },
        }
        const result = await handelNotice(customMsg, store)
        store.commit('saveSelectSession', result)
      }
      store.commit('savePageIndex', 0)
      store.commit('saveDialogState', false)
      emit('submit')
    }
    const editRemarkAction = () => {
      if (data.value.myGroupNickname === '') return
      editName({ groupId: props?.groupId, name: data.value.myGroupNickname })
    }
    return {
      editRemarkAction,
      data,
      enterGroup,
      logoutAction,
      editName
    }
  }
})
</script>

<style scoped lang="less">
.noButton {
  .sm {
    height: 300px !important;
  }
}

@import url('./styles.less');
</style>
